// ignore_for_file: sort_constructors_first, unnecessary_this

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:medical_pro_flutter/api/Api.dart';
import 'package:medical_pro_flutter/components/dialog/FailDialog.dart';
import 'package:medical_pro_flutter/components/dialog/LoadingDialog.dart';
import 'package:medical_pro_flutter/components/dialog/SuccessDialog.dart';
import 'package:medical_pro_flutter/entity/User.dart';

import '../../components/widget/ExpertOrNot.dart';
import '../../utils/StringUtils.dart';
import '../dialog/ExpertListDialog.dart';
import '../dialog/ImageDialog.dart';

// 本页展示刚post过后的病例，从这里可以推送给某个专家，ShowCasePage只是展示信息，不可以推送或修改信息

class ShowPostCasePage extends StatefulWidget {
  Map? arguments;
  ShowPostCasePage({this.arguments});

  @override
  _ShowPostCasePageState createState() =>
      _ShowPostCasePageState(arguments: this.arguments);
}

class _ShowPostCasePageState extends State<ShowPostCasePage> {
  Map? arguments;
  List? imageList = [];
  List? seg_image_List = [];
  Widget _selectedExpertJobNumWidget = ExpertOrNotWidget(arguments: '');
  String _selectedExpertJobNum = '';
  String _selectedExpertName = '';
  bool _showSelectedExpertJobNum = true;
  bool _showSelectExpert = false;
  bool _showExpertSug = true;
  bool _showSegPhotowButton = false;

  _ShowPostCasePageState({this.arguments});

  TextEditingController nameController = TextEditingController();
  TextEditingController idController = TextEditingController();
  TextEditingController phonenumController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  TextEditingController habitStrController = TextEditingController(text: '无');
  TextEditingController historyController = TextEditingController();
  TextEditingController resultController = TextEditingController();
  TextEditingController sugController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    nameController.text = arguments!['patient_name'];
    idController.text = arguments!['patient_idcard_num'];
    phonenumController.text = arguments!['phone_num'];
    ageController.text = arguments!['patient_age'].toString();
    resultController.text = arguments!['result'];

    if (arguments!['expert_sug_list'].isEmpty) {
      sugController.text = '暂无专家建议';
      _showSelectExpert = false;
      _showExpertSug = true;
    }

    if (arguments!['allergy_history'] == 'y') {
      historyController.text = '有';
    } else {
      historyController.text = '无';
    }

    habitStrController.text = '无';

    if (arguments!['habits'].contains(2)) {
      if (habitStrController.text == '无') {
        habitStrController.text = '';
        habitStrController.text = habitStrController.text + ' 喝酒';
      } else {
        habitStrController.text = habitStrController.text + ' 喝酒';
      }
    }

    if (arguments!['habits'].contains(1)) {
      if (habitStrController.text == '无') {
        habitStrController.text = '';
        habitStrController.text = habitStrController.text + ' 抽烟';
      } else {
        habitStrController.text = habitStrController.text + ' 抽烟';
      }
    }

    if (arguments!['habits'].contains(3)) {
      if (habitStrController.text == '无') {
        habitStrController.text = '';
        habitStrController.text = habitStrController.text + ' 熬夜';
      } else {
        habitStrController.text = habitStrController.text + ' 熬夜';
      }
    }

    print('展示页面：${arguments!['image_names']}');
    print('前：${imageList.toString()}');

    arguments!['image_names'].forEach((v) {
      print(v);

      imageList?.add(
          StringUtils.getCaseImageUrl(arguments!['case_id'].toString(), v));
    });

    print('后：${imageList.toString()}');
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        alignment: Alignment.center,
        margin: const EdgeInsets.all(20),
        padding: const EdgeInsets.all(5),
        child: Column(
          children: <Widget>[
            Container(
                margin: const EdgeInsets.all(10),
                child: TextField(
                  enabled: false,
                  controller: nameController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(), labelText: '姓名'),
                )),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextField(
                enabled: false,
                controller: idController,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '身份证号'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextField(
                enabled: false,
                keyboardType: TextInputType.number,
                controller: phonenumController,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '联系电话'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextField(
                enabled: false,
                keyboardType: TextInputType.number,
                controller: ageController,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '年龄'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextField(
                enabled: false,
                keyboardType: TextInputType.number,
                controller: habitStrController,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '习惯'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextField(
                enabled: false,
                keyboardType: TextInputType.number,
                controller: historyController,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '过敏史'),
              ),
            ),
            SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: ImageWrap(),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextField(
                keyboardType: TextInputType.multiline,
                // maxLines: whatever,
                enabled: false,
                maxLines: null,
                controller: resultController,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '诊断结果'),
              ),
            ),
            SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: ImageWrap_Seg(),
            ),
            Offstage(
                offstage: _showSegPhotowButton,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    // ElevatedButton(
                    //   child: Text('获取分割图'),
                    //   onPressed: _getSegPhotoUrl,
                    //   style: ButtonStyle(
                    //     backgroundColor: MaterialStateProperty.all(Colors.blue),
                    //   ),
                    // ),
                  ],
                )),
            Offstage(
              offstage: _showSelectExpert,
              child: Column(
                children: [
                  Divider(),
                  Text('还是不能判断？选个专家推送给他'),
                  ElevatedButton(
                    child: Text("选择专家"),
                    onPressed: () async {
                      var va = await showDialog(
                          context: context,
                          builder: (context) {
                            return ExpertListDialog();
                          });
                      print('传来了${va.toString()}');
                      setState(() {
                        if (va != null) {
                          _selectedExpertJobNum = va["job_num"].toString();
                          _selectedExpertName = va["name"].toString();
                          _showSelectedExpertJobNum = false;
                        }
                        print('设置值：${va.toString()}');
                      });
                    },
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Colors.blue),
                    ),
                  ),
                  Offstage(
                      offstage: _showSelectedExpertJobNum,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.only(right: 58.0),
                            child: Text('推送给专家：$_selectedExpertName'),
                          ),
                          ElevatedButton(
                            child: Text("确认推送"),
                            onPressed: _postPushCase,
                            style: ButtonStyle(
                              backgroundColor:
                                  MaterialStateProperty.all(Colors.blue),
                            ),
                          ),
                        ],
                      ))
                ],
              ),
            ),
            Offstage(
              offstage: _showExpertSug,
              child: TextField(
                keyboardType: TextInputType.multiline,
                // maxLines: whatever,
                enabled: false,
                maxLines: null,
                controller: sugController,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '专家建议'),
              ),
            ),
            ElevatedButton(
              child: Text("返回"),
              onPressed: () {
                Navigator.pop(context);
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.blue),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget ImageWrap() {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: Wrap(
        runSpacing: 10,
        spacing: 5,
        children: initFile(),
      ),
    );
  }

  Widget ImageWrap_Seg() {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: Wrap(
        runSpacing: 10,
        spacing: 5,
        children: initFile_Seg(),
      ),
    );
  }

  initFile() {
    return imageList!
        .map((file) => Stack(
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return ImageDialog(file);
                        });
                  },
                  child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      child: Image.network(
                        file,
                        width: 100,
                        height: 100,
                        fit: BoxFit.fill,
                      )),
                )
              ],
            ))
        .toList();
  }

  _getSegPhotoUrl() async {
    Response response;
    String url = API.BASE_URL +
        API.GET_SEG_PHOTO_LIST +
        arguments!['case_id'].toString();
    var dio = Dio();
    response = await dio.get(url);
    dio.close();

    if (response.statusCode == 200) {
      print(response.data);
      List<dynamic> res = json.decode(response.data);
      for (int i = 0; i < res.length; i++) {
        res[i] = StringUtils.getSegImageUrl(
            arguments!['case_id'].toString(), res[i]);
      }
      setState(() {
        seg_image_List = res;
        _showSegPhotowButton = true;
      });

      // List va = List<dynamic>.from(response.data);

      // va.forEach((v) {
      //   print(v);

      //   setState(() {
      //     seg_image_List!.add(
      //         StringUtils.getSegImageUrl(arguments!['case_id'].toString(), v));
      //   });
      // });
    }
  }

  initFile_Seg() {
    return seg_image_List!
        .map((file) => Stack(
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return ImageDialog(file);
                        });
                  },
                  child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      child: Image.network(
                        file,
                        width: 100,
                        height: 100,
                        fit: BoxFit.fill,
                      )),
                )
              ],
            ))
        .toList();
  }

  _postPushCase() async {
    String url = API.BASE_URL + API.POST_PUSHCASE;
    Response response;

    try {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return LoadingDialog(text: '加载中...');
          });

      var dio = Dio();
      var formData = FormData.fromMap({
        'pusher_job_num': User.job_num,
        'receiver_job_num': _selectedExpertJobNum,
        'case_id': arguments!['case_id'],
      });
      response = await dio.post(url, data: formData);
      print('code:${response.statusCode}');

      if (response.statusCode == 200) {
        // Map<String, dynamic> changedInfo = json.decode(response.data);
        // Map<String, dynamic> changedInfo =
        //     Map<String, dynamic>.from(response.data);

        var pushInfo = response.data;

        Navigator.pop(context);
        if (pushInfo == '1') {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return SuccessDialog(text: '推送成功');
              });
        } else {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return FailDialog(text: '已经推送过了');
              });
        }
      }
    } catch (e) {
      print(e.toString());
      Navigator.pop(context);

      showDialog(
          context: context,
          builder: (BuildContext context) {
            return FailDialog(text: '修改失败');
          });
    }
    setState(() {
      _showExpertSug = false;
      _showSelectExpert = true;
    });
  }
}
